package com.pudu.mydemo.utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.pudu.mydemo.entity.Update;
import com.pudu.mydemo.remote.RobotApi;
import com.pudu.mydemo.service.DownloadService;
import com.pudu.pdrobot.App;

import org.json.JSONException;

import cz.msebera.android.httpclient.Header;
import java.io.ByteArrayInputStream;

/**
 * Created by guiliu on 2016/8/29.
 */
public class UpdateManager implements  DownloadService.updatelistener, DownloadService.onErrorListener{
    private Update mUpdate;
    private Context mContext;
    private boolean isShow = false;
    private ProgressDialog _waitDialog;

    public UpdateManager(Context context, boolean isShow) {
        this.mContext = context;
        this.isShow = isShow;
    }

    private ProgressDialog mProgressDialog;

    private void setProgressDialog() {
        mProgressDialog = new ProgressDialog(mContext);
        mProgressDialog.setMessage("download");
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setMax(100);
        mProgressDialog.show();
    }

    private AsyncHttpResponseHandler mCheckUpdateHandle = new AsyncHttpResponseHandler() {

        @Override
        public void onFailure(int arg0, Header[] arg1, byte[] arg2,
                              Throwable arg3) {
            hideCheckDialog();
            if (isShow) {
                showFaileDialog();
            }
        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
            hideCheckDialog();
           /* mUpdate = XmlUtils.toBean(Update.class,
                    new ByteArrayInputStream(arg2));*/
            Log.e("success","bytes:"+arg2.toString()
            );
            String json = new String(arg2);
            Log.e("success","json:"+json);
            Gson gson = new Gson();
            mUpdate = gson.fromJson(json, Update.class);
            if(mUpdate!= null) Log.e("success","update code:"+mUpdate.getVersionCode()+" version name:"+mUpdate.getVersionName()+"url:"+mUpdate.getDownLoadUrl());
//            mUpdate.setVersionCode(264);
//            mUpdate.setVersionName("v2.6.4(1608081154)");
//            mUpdate.setDownLoadUrl("http://www.pudutech.com/update/net.oschina.app_v2.6.4(1608081154)_264.apk");
            onFinshCheck();
        }
    };
    public boolean haveNew() {
        if(this.mUpdate == null) {
            return false;
        }
        boolean hasNew = false;
        int curVersionCode = TDevice.getVersionCode(App.context().getPackageName());
        if(curVersionCode < mUpdate.getVersionCode()) {
            //need to update
            hasNew = true;
        }
        return hasNew;
    }

    public void checkUpdate() {
        if (isShow) {
            showCheckDialog();
        }
        RobotApi.checkUpdate(mCheckUpdateHandle);
    }

    private void onFinshCheck() {
        if (haveNew()) {
            showUpdateInfo();
        } else {
            if (isShow) {
                showLatestDialog();
            }
        }
    }

    private void showCheckDialog() {
        if (_waitDialog == null) {
            _waitDialog = DialogHelp.getWaitDialog((Activity) mContext, "正在获取新版本信息...");
        }
        _waitDialog.show();
    }

    private void hideCheckDialog() {
        if (_waitDialog != null) {
            _waitDialog.dismiss();
        }
    }

    private void showUpdateInfo() {
        if (mUpdate == null) {
            return;
        }
        AlertDialog.Builder dialog = DialogHelp.getConfirmDialog(mContext, "每一次升级，我们竭尽全力为广大普渡用户们提供更优质的服务"/* mUpdate.getUpdateLog()*/, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                openDownLoadService(mContext, mUpdate.getDownLoadUrl(), mUpdate.getVersionName());
                setProgressDialog();
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                SpUtils.set("not_update_this_time",true);
                App.isUpdate = false;
            }
        });
        dialog.setTitle("发现新版本");
        dialog.show();
    }



    private void showLatestDialog() {
        DialogHelp.getMessageDialog(mContext, "已经是新版本了").show();
    }

    private void showFaileDialog() {
        DialogHelp.getMessageDialog(mContext, "网络异常，无法获取新版本信息").show();
    }

    public  void openDownLoadService(final Context context, String downurl,
                                           String tilte) {
        /*final ICallbackResult callback = new ICallbackResult() {

            @Override
            public void OnBackResult(Object s) {}
        };*/
        ServiceConnection conn = new ServiceConnection() {

            @Override
            public void onServiceDisconnected(ComponentName name) {}

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                DownloadService.DownloadBinder binder = (DownloadService.DownloadBinder) service;
//                binder.addCallback(callback);
                Log.e("success","has binder");
                binder.setupdateListener(UpdateManager.this);
                binder.setErrorListener(UpdateManager.this);
                binder.start();

            }
        };
        Intent intent = new Intent(context, DownloadService.class);
        intent.putExtra(DownloadService.BUNDLE_KEY_DOWNLOAD_URL, downurl);
        intent.putExtra(DownloadService.BUNDLE_KEY_TITLE, tilte);
        context.startService(intent);
        context.bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void updateProgress(int progress) {
        Log.e("success","updateProgress progress:"+progress);
        mProgressDialog.setIndeterminate(false);
//        mProgressDialog.setMax(100);
        mProgressDialog.setProgress(progress);
        if(progress == 100) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public void onError() {
        if(mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            Toast.makeText(mContext,"下载出错", Toast.LENGTH_LONG).show();
        }
    }
}
